package edu.uob;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class addAttribute {
    public static String add(String tableName, String attributeName) {
        Path tablePath = getTablePath(tableName);
        if (Files.exists(tablePath)) {
            try (Stream<String> linesStream = Files.lines(tablePath)) {
                List<String> lines = linesStream.collect(Collectors.toList());
                String firstLine = lines.isEmpty() ? null : lines.get(0);
                if (firstLine != null) {
                    if (firstLine.contains(attributeName)) {
                        return "[ERROR]: Attribute '" + attributeName + "' already exists.";
                    } else {
                        String updatedFirstLine = firstLine + "\t" + attributeName;
                        lines.set(0, updatedFirstLine);
                        for (int i = 1; i < lines.size(); i++) {
                            lines.set(i, lines.get(i) + "\t" + " "); // 根据实际情况设置默认值
                        }
                        Files.write(tablePath, lines, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);
                        return "[OK]";
                    }
                } else {
                    return "[ERROR]: The file is empty.";
                }
            } catch (IOException e) {
                return "[ERROR]: Failed to read/write the file: " + e.getMessage();
            }
        } else {
            return "[ERROR]: Table does not exist.";
        }
    }

    private static Path getTablePath(String tableName) {
        String file_name = "." + File.separator + "databases" + File.separator + CmdType.getDbName() + File.separator + tableName + ".tab";
        return Paths.get(file_name);
    }
}
